package so.sao.service.order;

import com.github.pagehelper.PageHelper;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import so.sao.dao.TbOrderDetailsMapper;
import so.sao.dao.TbOrderMapper;
import so.sao.domain.BaseEntity;
import so.sao.domain.TbOrder;
import so.sao.domain.TbOrderDetails;
import so.sao.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * @author  gxy on 2017/7/10.
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private TbOrderMapper orderMapper;
    @Autowired
    private TbOrderDetailsMapper orderDetailsMapper;

    /**
     * 分页获取所有订单.
     * @return List<TbOrder>
     */
    @Override
    public List<TbOrder> getOrders(int pageNum) {
        BaseEntity baseEntity = new BaseEntity();
        if(pageNum == 0) {
            pageNum = 1;
        }
        PageHelper.startPage(pageNum,baseEntity.getRows());
        List<TbOrder> orderList =orderMapper.findAll();
        getMethod(orderList);
        return orderList;
    }

    /**
     * 根据状态值分页获取所有订单.
     * @param status
     * @return List<TbOrder>
     */
    @Override
    public List<TbOrder> getOrderListByStatus(String status, int pageNum) {
        BaseEntity baseEntity = new BaseEntity();
        if(pageNum == 0) {
            pageNum = 1;
        }
        PageHelper.startPage(pageNum,baseEntity.getRows());
        List<TbOrder> orderList =  orderMapper.getOrderListByStatus(status);
        getMethod(orderList);
        return orderList;
    }

    /**
     * 根据订单Id获取订单详情.
     * @param orderId
     * @return List<TbOrderDetails>
     */
    @Override
    public List<TbOrderDetails> getOrderDetailByOId(String orderId) {
        return orderDetailsMapper.getOrderDetailByOId(orderId);
    }

    /**
     * 更改某个订单的状态值.
     * @param status
     * @param orderId
     * @return int 1成功0失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateOrderStatus(String status, String orderId) throws Exception {
        TbOrder tbOrder = new TbOrder();
        tbOrder.setOrder_stute(status);
        tbOrder.setOrder_id(orderId);
        return orderMapper.updateByPrimaryKeySelective(tbOrder);
    }

    /**
     * POI导出Excel
     * @param request
     * @param response
     * @param status
     */
    @Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse response, String status) {
        //创建HSSFWorkbook对象(excel的文档对象)
        HSSFWorkbook wb = new HSSFWorkbook();
        //声明一个单子并命名
        HSSFSheet sheet = wb.createSheet("订单统计");
        for (int i = 0; i < 10; i++) {
            sheet.setColumnWidth(i, 25 * 256);
        }
        // 生成一个样式
        HSSFCellStyle style = wb.createCellStyle();

        //创建第一行（也可以称为表头）
        HSSFRow row = sheet.createRow(0);
        row.setHeightInPoints(30);
        //样式字体居中
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        //给表头第一行一次创建单元格
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("订单编号");
        cell.setCellStyle(style);

        cell = row.createCell(1);
        cell.setCellValue("商品名称");
        cell.setCellStyle(style);

        cell = row.createCell(2);
        cell.setCellValue("收货人");
        cell.setCellStyle(style);

        cell = row.createCell(3);
        cell.setCellValue("联系电话");
        cell.setCellStyle(style);

        cell = row.createCell(4);
        cell.setCellValue("订单状态");
        cell.setCellStyle(style);

        cell = row.createCell(5);
        cell.setCellValue("订单金额");
        cell.setCellStyle(style);

        cell = row.createCell(6);
        cell.setCellValue("下单时间");
        cell.setCellStyle(style);

        //根据status获取order集合
        List<TbOrder> orderList = orderMapper.getOrderListByStatus(status);
        if(orderList != null && orderList.size() > 0) {
            for(int i=0; i<orderList.size(); i++){
                List<TbOrderDetails> tbOrderDetailsList = orderDetailsMapper.getOrderDetailByOId(orderList.get(i).getOrder_id());
                String sb = "";
                if(tbOrderDetailsList != null && tbOrderDetailsList.size() > 0) {
                    for(int j=0; j<tbOrderDetailsList.size(); j++) {
                        sb += tbOrderDetailsList.get(j).getCommodity_name()+",";
                    }
                    if(!"".equals(sb)){
                        orderList.get(i).setCommodity_name(sb.substring(0,sb.length()-1));
                    }
                } else {
                    orderList.get(i).setCommodity_name(sb);
                }
            }
        }
        //向单元格里填充数据
        HSSFCell cellTemp = null;
        for (int i = 0; i < orderList.size(); i++) {
            TbOrder order = orderList.get(i);
            sheet.setColumnWidth(0, 20 * 256);
            row = sheet.createRow(i + 1);
            cellTemp = row.createCell(0);
            cellTemp.setCellValue(order.getOrder_id());
            cellTemp.setCellStyle(style);
            cellTemp = row.createCell(1);
            cellTemp.setCellValue(order.getCommodity_name());
            cellTemp.setCellStyle(style);
            cellTemp = row.createCell(2);
            cellTemp.setCellValue(order.getOrder_consignee());
            cellTemp.setCellStyle(style);
            cellTemp = row.createCell(3);
            cellTemp.setCellValue(order.getOrder_phone());
            cellTemp.setCellStyle(style);
            cellTemp = row.createCell(4);
            cellTemp.setCellValue(order.getOrder_stute());
            cellTemp.setCellStyle(style);
            cellTemp = row.createCell(5);
            cellTemp.setCellValue(order.getOrder_money()+"￥");
            cellTemp.setCellStyle(style);
            cellTemp = row.createCell(6);
            cellTemp.setCellValue(order.getOrder_longtime() == null ? "" : StringUtil.fomateData(order.getOrder_longtime(),"yyyy-MM-dd HH:mm:ss"));
            cellTemp.setCellStyle(style);
        }
        //输出Excel文件
        OutputStream output = null;
        try {
            output = response.getOutputStream();
            response.reset();
            String agent = request.getHeader("USER-AGENT").toLowerCase();
            response.setContentType("application/vnd.ms-excel");
            String fileName = "订单统计" + System.currentTimeMillis();
            String codedFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            if (agent.contains("firefox")) {
                response.setCharacterEncoding("utf-8");
                response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1") + ".xls");
            } else {
                response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
            }
            wb.write(output);
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 往每个订单添加订单详情
     * @param orderList
     */
    private void getMethod(List<TbOrder> orderList) {
        if(orderList != null && orderList.size() > 0) {
            for(int i=0; i<orderList.size(); i++) {
                List<TbOrderDetails> orderDetailsList = orderDetailsMapper.getOrderDetailByOId(orderList.get(i).getOrder_id());
                if(orderDetailsList != null && orderDetailsList.size() > 0){
                    orderList.get(i).setOrderDetailsList(orderDetailsList);
                }
            }
        }
    }
}
